<template>
  <view class="page">
    <view v-if="!order._id" class="loading">
      <view style="text-align: center; padding: 100rpx 32rpx;">
        <view style="font-size: 28rpx; color: #999;">加载中...</view>
      </view>
    </view>
    <view v-else class="order-wrapper">
      <scroll-view class="order-scroll">
        <view class="order-detail">
          <!-- 订单状态卡片 -->
          <view class="status-card" :class="'status-' + order.status">
            <view class="status-text">{{ getStatusText(order.status) }}</view>
            <view class="order-no">{{ order.order_no }}</view>
          </view>

          <!-- 菜品清单 -->
          <view class="section">
            <view class="section-title">菜品清单</view>
            <view class="dishes-list">
              <view v-for="(dish, index) in order.dishes" :key="index" class="dish-item">
                <view class="dish-info">
                  <view class="dish-name">{{ dish.name }}</view>
                </view>
                <view class="dish-qty">× {{ dish.count }}</view>
              </view>
            </view>
          </view>

          <!-- 订单信息 -->
          <view class="section">
            <view class="section-title">订单信息</view>
            <view class="info-grid">
              <view class="info-item">
                <view class="info-label">订单时间</view>
                <view class="info-value">{{ formatFullTime(order.create_date) }}</view>
              </view>
              <view class="info-item">
                <view class="info-label">菜品总数</view>
                <view class="info-value">{{ order.dishes.length }} 种</view>
              </view>
              <view class="info-item">
                <view class="info-label">份数</view>
                <view class="info-value">{{ getTotalCount() }} 份</view>
              </view>
            </view>
          </view>

          <!-- 备注 -->
          <view v-if="order.remarks" class="section">
            <view class="section-title">备注</view>
            <view class="remarks-meta">
              <view class="remarks-time">{{ formatFullTime(order.create_date) }}</view>
            </view>
            <view class="remarks-box">{{ order.remarks }}</view>
          </view>

          <!-- 状态时间记录 -->
          <view class="section">
            <view class="section-title">状态时间记录</view>
            <view class="timeline-record">
              <view v-if="order.status_time?.created" class="timeline-item">
                <view class="timeline-time">{{ formatFullTime(order.status_time.created) }}</view>
                <view class="timeline-status">订单创建</view>
              </view>
              <view v-if="order.status_time?.accepted" class="timeline-item">
                <view class="timeline-time">{{ formatFullTime(order.status_time.accepted) }}</view>
                <view class="timeline-status">已接单</view>
              </view>
              <view v-if="order.status_time?.started" class="timeline-item">
                <view class="timeline-time">{{ formatFullTime(order.status_time.started) }}</view>
                <view class="timeline-status">开始制作</view>
              </view>
              <view v-if="order.status_time?.completed" class="timeline-item">
                <view class="timeline-time">{{ formatFullTime(order.status_time.completed) }}</view>
                <view class="timeline-status">已完成</view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 操作按钮 -->
      <view class="actions-section">
        <button 
          v-if="order.status === 0"
          size="default"
          type="default"
          class="btn btn-primary"
          style="color: #fff; background-color: #10b981; border-color: #10b981;"
          hover-class="btn-primary-hover"
          @click="acceptOrder"
        >
          接单
        </button>
        <view 
          v-if="order.status === 1"
          class="btn-group"
        >
          <button 
            size="default"
            type="default"
            class="btn btn-purchase"
            style="color: #10b981; background-color: #fff; border-color: #10b981; border-width: 2rpx;"
            hover-class="btn-purchase-hover"
            @click="goToPurchaseList"
          >
            采购清单
          </button>
          <button 
            size="default"
            type="default"
            class="btn btn-primary"
            style="color: #fff; background-color: #10b981; border-color: #10b981;"
            hover-class="btn-primary-hover"
            @click="startCooking"
          >
            开始制作
          </button>
        </view>
        <button 
          v-if="order.status === 2"
          size="default"
          type="default"
          class="btn btn-primary"
          style="color: #fff; background-color: #10b981; border-color: #10b981;"
          hover-class="btn-primary-hover"
          @click="completeOrder"
        >
          完成
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const order = ref({
  _id: '',
  order_no: '',
  dishes: [],
  status: 0,
  create_date: null,
  status_time: {},
  remarks: ''
})

function getStatusText(status) {
  const statusMap = {
    0: '待处理',
    1: '已接单',
    2: '制作中',
    3: '已完成',
    '-1': '已取消'
  }
  return statusMap[status] || '未知状态'
}

function getTotalCount() {
  return order.value.dishes.reduce((sum, dish) => sum + (dish.count || 1), 0)
}

function formatFullTime(timestamp) {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

async function loadOrderDetail(orderId) {
  uni.showLoading({ mask: true })
  try {
    const res = await uniCloud.callFunction({
      name: 'food-order',
      data: {
        action: 'get-order-detail',
        data: {
          order_id: orderId
        }
      }
    })

    if (res.result && res.result.code === 200) {
      order.value = res.result.data
    } else {
      uni.showToast({
        title: res.result?.message || '加载失败',
        icon: 'none'
      })
    }
  } catch (err) {
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

async function acceptOrder() {
  try {
    const res = await uniCloud.callFunction({
      name: 'food-order',
      data: {
        action: 'update-order-status',
        data: {
          orderId: order.value._id,
          status: 1
        }
      }
    })

    if (res.result && res.result.code === 200) {
      uni.showToast({ title: '已接单', icon: 'success' })
      order.value.status = 1
      order.value.status_time = res.result.data.statusTime
    } else {
      uni.showToast({ title: res.result?.message || '操作失败', icon: 'none' })
    }
  } catch (err) {
    uni.showToast({ title: '操作失败', icon: 'none' })
  }
}

async function startCooking() {
  try {
    const res = await uniCloud.callFunction({
      name: 'food-order',
      data: {
        action: 'update-order-status',
        data: {
          orderId: order.value._id,
          status: 2
        }
      }
    })

    if (res.result && res.result.code === 200) {
      uni.showToast({ title: '开始制作', icon: 'success' })
      order.value.status = 2
      order.value.status_time = res.result.data.statusTime
    } else {
      uni.showToast({ title: res.result?.message || '操作失败', icon: 'none' })
    }
  } catch (err) {
    uni.showToast({ title: '操作失败', icon: 'none' })
  }
}

async function completeOrder() {
  try {
    const res = await uniCloud.callFunction({
      name: 'food-order',
      data: {
        action: 'update-order-status',
        data: {
          orderId: order.value._id,
          status: 3
        }
      }
    })

    if (res.result && res.result.code === 200) {
      uni.showToast({ title: '已完成', icon: 'success' })
      order.value.status = 3
      order.value.status_time = res.result.data.statusTime
    } else {
      uni.showToast({ title: res.result?.message || '操作失败', icon: 'none' })
    }
  } catch (err) {
    uni.showToast({ title: '操作失败', icon: 'none' })
  }
}

function goBack() {
  uni.navigateBack()
}

function goToPurchaseList() {
  uni.navigateTo({
    url: `/pages/purchase-list/purchase-list?orderId=${order.value._id}`
  })
}

onLoad((options) => {
  if (options.id) {
    loadOrderDetail(options.id)
  }
})
</script>

<style lang="scss" scoped>
$primary-color: #10b981;
$danger-color: #ef4444;

.page {
  min-height: 100vh;
  background: #f8fafc;
  padding: 20rpx;
  padding-bottom: 20rpx;
  display: flex;
  flex-direction: column;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.order-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.order-scroll {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.order-detail {
  .status-card {
    background: linear-gradient(135deg, $primary-color, #059669);
    color: #fff;
    padding: 24rpx;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.2);

    &.status--1,
    &.status-0 {
      background: linear-gradient(135deg, #f59e0b, #f97316);
    }

    &.status-2 {
      background: linear-gradient(135deg, $primary-color, #06b6d4);
    }

    .status-text {
      font-size: 32rpx;
      font-weight: 600;
      margin-bottom: 8rpx;
    }

    .order-no {
      font-size: 24rpx;
      opacity: 0.9;
    }
  }

  .section {
    background: #fff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.06);

    .section-title {
      font-size: 28rpx;
      font-weight: 600;
      color: #0f172a;
      margin-bottom: 16rpx;
      padding-bottom: 12rpx;
      border-bottom: 1rpx solid #e5e7eb;
    }

    .dishes-list {
      .dish-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12rpx 0;
        border-bottom: 1rpx solid #e5e7eb;

        &:last-child {
          border-bottom: none;
        }

        .dish-info {
          flex: 1;

          .dish-name {
            font-size: 26rpx;
            color: #1f2937;
            margin-bottom: 4rpx;
          }
        }

        .dish-qty {
          font-size: 24rpx;
          color: #6b7280;
          font-weight: 600;
        }
      }
    }

    .info-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16rpx;

      .info-item {
        .info-label {
          font-size: 22rpx;
          color: #6b7280;
          margin-bottom: 6rpx;
        }

        .info-value {
          font-size: 26rpx;
          color: #1f2937;
          font-weight: 600;
        }
      }
    }

    .remarks-box {
      background: #f3f4f6;
      padding: 12rpx;
      border-radius: 8rpx;
      font-size: 24rpx;
      color: #374151;
      line-height: 1.6;
    }

    .remarks-meta {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 8rpx;
      padding-right: 12rpx;

      .remarks-time {
        font-size: 22rpx;
        color: #6b7280;
      }
    }

    .timeline-record {
      .timeline-item {
        padding: 12rpx 0;
        padding-left: 20rpx;
        border-left: 2rpx solid $primary-color;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          left: -8rpx;
          top: 16rpx;
          width: 12rpx;
          height: 12rpx;
          background: $primary-color;
          border-radius: 50%;
        }

        .timeline-time {
          font-size: 22rpx;
          color: #6b7280;
          margin-bottom: 4rpx;
        }

        .timeline-status {
          font-size: 24rpx;
          color: #1f2937;
          font-weight: 600;
        }
      }
    }
  }

  .actions-section {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    padding: 16rpx 20rpx;
    padding-bottom: max(80rpx, env(safe-area-inset-bottom));
    border-top: 1rpx solid #e5e7eb;
    box-shadow: 0 -6rpx 20rpx rgba(0, 0, 0, 0.06);
    display: flex;
    flex-direction: column;
    gap: 12rpx;

    .btn {
      height: 44rpx;
      border-radius: 10rpx;
      font-size: 28rpx;
      font-weight: 600;
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;

      &.btn-primary {
        &:active,
        &.btn-primary-hover {
          opacity: 0.9;
          box-shadow: 0 4rpx 12rpx rgba(16, 185, 129, 0.3);
        }
      }

      &.btn-purchase {
        &:active,
        &.btn-purchase-hover {
          background-color: #f9f9f9 !important;
        }
      }
    }

    .btn-group {
      display: flex;
      gap: 12rpx;
      width: 100%;
    }
  }
}
</style>

